package com.shaoshaohuo.app.ui;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.shaoshaohuo.app.R;
import com.shaoshaohuo.app.adapter.MyBaseAdapter;
import com.shaoshaohuo.app.entity.BaseEntity;
import com.shaoshaohuo.app.entity.DeliverQueryENtity;
import com.shaoshaohuo.app.net.ShopHttpConfig;
import com.shaoshaohuo.app.utils.ErroCodeUtils;
import com.shaoshaohuo.app.utils.Okhttputils;
import com.shaoshaohuo.app.utils.ToastUtil;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Response;

/**
 * 收貨地址介面
 * Created by Administrator on 2017/6/10.
 */

public class DeliveryaddressActivity extends BaseActivity implements SwipeRefreshLayout.OnRefreshListener {

    private ListView delivery_address_list;
    private LinearLayout delivery_address_lin_zw;
    private ArrayList<DeliverQueryENtity.DataBean> dataBeen;
    private SwipeRefreshLayout delivery_address_swp;
    private Myadapter myadapter;
    private Handler handler = new Handler();
    private Button addnewAderss;
    private boolean isfulsh = true;
    private Bundle bundle;
    private String no_have_address;//判断苁购物车跳过来是有无地址


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.deliveryaddresslayout);
        delivery_address_list = (ListView) findViewById(R.id.Delivery_address_list);
        delivery_address_lin_zw = (LinearLayout) findViewById(R.id.Delivery_address_lin_zw);
        delivery_address_list.setEmptyView(delivery_address_lin_zw);
        bundle = getIntent().getExtras();
        inittopbarview();
        changeTransltestaus(((ViewGroup) getWindow().getDecorView().findViewById(android.R.id.content)).getChildAt(0), this, TransltestausModel.NoePicter, getResources().getColor(R.color.color_49b152));
    }

    private void inittopbarview() {
        findViewById(R.id.imageview_message).setVisibility(View.GONE);
        TextView toolbar_topname = (TextView) findViewById(R.id.toolbar_topname);
        toolbar_topname.setText("收货地址");

        //imageview_topbar_left_backImage
        View viewById = findViewById(R.id.imageview_topbar_left_backImage);
        viewById.setVisibility(View.VISIBLE);
        viewById.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (bundle != null) {
                    if (bundle.get("type").equals("1")) {
                        no_have_address = (String) bundle.get("have_no_address");
                        Log.e("带回的数据", no_have_address);
                        if (no_have_address.equals("110")) {
                            Intent intent = new Intent();
                            setResult(110, intent);
                        } else if (no_have_address.equals("119")) {
                            Intent intent = new Intent();
                            setResult(119, intent);
                        }
                    }
                    finish();//返回购物车界面
                } else {
                    finish();//返回我的界面
                }
            }
        });
        //收貨地址的按鈕
        addnewAderss = (Button) findViewById(R.id.addnewAderss);
        addnewAderss.setVisibility(View.GONE);
        //刷新
        delivery_address_swp = (SwipeRefreshLayout) findViewById(R.id.Delivery_address_swp);
        delivery_address_swp.setOnRefreshListener(this);
        //setDistanceToTriggerSync
//        delivery_address_swp.setDistanceToTriggerSync(500);
        dataBeen = new ArrayList<>();
        myadapter = new Myadapter(this, dataBeen, true);
        delivery_address_list.setAdapter(myadapter);
        delivery_address_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                ToastUtil.toast("" + position);
                if (bundle != null) {
                    if (bundle.get("type").equals("1")) {//区别是返回购物车还是返回我的界面
                        no_have_address = (String) bundle.get("have_no_address");
                        Log.e("带回的数据", no_have_address);
                        if (no_have_address.equals("110")) {
                            Intent intent = new Intent();
                            setResult(110, intent);
                        } else if (no_have_address.equals("119")) {
                            List<DeliverQueryENtity.DataBean> getdata = myadapter.getdata();
                            DeliverQueryENtity.DataBean dataBean = getdata.get(position);
                            /**
                             * 添加需求的數據
                             */
                            Intent intent = new Intent();
                            intent.putExtra("back_data", dataBean);
                            setResult(119, intent);
                        }
                        finish();
                    }
                }
            }
        });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (bundle != null) {
                if (bundle.get("type").equals("1")) {
                    no_have_address = (String) bundle.get("have_no_address");
                    Log.e("带回的数据", no_have_address);
                    if (no_have_address.equals("110")) {
                        Intent intent = new Intent();
                        setResult(110, intent);
                    } else if (no_have_address.equals("119")) {
                        Intent intent = new Intent();
                        setResult(119, intent);
                    }
                }
                finish();//返回购物车界面
            } else {
                finish();//返回我的界面
            }

            return true;
        }
        return false;
    }

    public void addnewAderss(View view) {
        //新增收货地址
//imageview_topbar_left_backImage
        Intent intent = new Intent();
        intent.setClass(this, NewaddAdders.class);
        startActivity(intent);

    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        Log.e("TAG", "onWindowFocusChanged: ");
        if (hasFocus) {
            delivery_address_swp.post(new Runnable() {
                @Override
                public void run() {
                    Log.e("TAG", "post: ");
                    delivery_address_swp.setRefreshing(true);
                    onRefresh();

                }
            });
        }

    }

    /**
     * 网络请求
     */
    public void netdate() {
        ShopHttpConfig.Addresssearch(this, "2", new Okhttputils.OkutListener() {
            @Override
            public void error(Call call, IOException e) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        delivery_address_lin_zw.setClickable(true);
                        delivery_address_swp.setRefreshing(false);
                        ToastUtil.toast("請檢查您的網絡");
                    }
                });
            }

            @Override
            public void error(Call call, final int code) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        delivery_address_swp.setRefreshing(false);
                        String errcode = ErroCodeUtils.errcode(code);
//                        ToastUtil.toast(errcode + code);
                        if (code == 220) {
                            handler.post(new Runnable() {
                                @Override
                                public void run() {
                                    myadapter.setData(new ArrayList<DeliverQueryENtity.DataBean>());
                                    addnewAderss.setVisibility(View.GONE);
                                    delivery_address_lin_zw.setClickable(true);
                                    delivery_address_swp.setRefreshing(false);
                                }
                            });

                        }

                    }
                });
            }

            @Override
            public void suseff(Call call, Response response, Object o) {
                final DeliverQueryENtity eNtity = (DeliverQueryENtity) o;
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        myadapter.setData(eNtity.getData());
                        if (eNtity.getData().size() > 0) {
                            addnewAderss.setVisibility(View.VISIBLE);
                        } else {
                            addnewAderss.setVisibility(View.GONE);
                        }
                        if (eNtity.getData().size() > 0) {
//                            delivery_address_lin_zw.setClickable(false);
                        } else {
                            delivery_address_lin_zw.setClickable(true);
                        }

                        delivery_address_swp.setRefreshing(false);
                    }
                });

            }
        }, DeliverQueryENtity.class);
    }

    @Override
    public void onRefresh() {
        netdate();
    }

    class Myadapter extends MyBaseAdapter<DeliverQueryENtity.DataBean> implements View.OnClickListener {

        private LayoutInflater from;

        public Myadapter(Context ctx, List<DeliverQueryENtity.DataBean> list, boolean flag) {
            super(ctx, list, flag);
            from = LayoutInflater.from(ctx);
        }


        @Override
        public View getView(int pos, View view, ViewGroup group) {
            ViewHolder mv;
            if (view == null) {
                view = from.inflate(R.layout.ac_deliverylistitem, null);
                mv = new ViewHolder();
                mv.deliveraddress_item_bian = (ImageView) view.findViewById(R.id.deliveraddress_item_bian);
                mv.deliveraddress_item_delete = (ImageView) view.findViewById(R.id.deliveraddress_item_delete);
                mv.deliveraddress_item_defultadderss = (TextView) view.findViewById(R.id.deliveraddress_item_defultadderss);
                mv.deliveraddress_item_tv_adresstype = (TextView) view.findViewById(R.id.deliveraddress_item_tv_adresstype);
                mv.tv_name = (TextView) view.findViewById(R.id.deliveraddress_item_name);
                mv.deliveraddress_item_tv_city = (TextView) view.findViewById(R.id.deliveraddress_item_tv_city);
                mv.deliveraddress_item_tv_county = (TextView) view.findViewById(R.id.deliveraddress_item_tv_county);
                mv.deliveraddress_item_tv_details = (TextView) view.findViewById(R.id.deliveraddress_item_tv_details);
                mv.deliveraddress_item_tv_phonenum = (TextView) view.findViewById(R.id.deliveraddress_item_tv_phonenum);
                mv.deliveraddress_item_tv_province = (TextView) view.findViewById(R.id.deliveraddress_item_tv_province);
                view.setTag(mv);
            } else {
                mv = (ViewHolder) view.getTag();
            }
            mv.deliveraddress_item_bian.setOnClickListener(this);
            mv.deliveraddress_item_bian.setTag(pos);
            mv.deliveraddress_item_delete.setOnClickListener(this);
            mv.deliveraddress_item_delete.setTag(pos);
            DeliverQueryENtity.DataBean dataBean = list.get(pos);
            //-地址的唯一id
            String addressid = dataBean.getAddressid();
            //地区
            String county = dataBean.getCounty();
            mv.deliveraddress_item_tv_county.setText(county);
            String city = dataBean.getCity();
            mv.deliveraddress_item_tv_city.setText(city);
            String defaultX = dataBean.getDefaultX();
            if (defaultX.equals("2")) {
                mv.deliveraddress_item_defultadderss.setVisibility(View.GONE);
            } else {
                mv.deliveraddress_item_defultadderss.setVisibility(View.VISIBLE);
            }
            String details = dataBean.getDetails();
            mv.deliveraddress_item_tv_details.setText(details + dataBean.getAddressnum());
            String name = dataBean.getName();
            mv.tv_name.setText(name);
            String phone = dataBean.getPhone();
            mv.deliveraddress_item_tv_phonenum.setText(phone);
            String province = dataBean.getProvince();
            mv.deliveraddress_item_tv_province.setText(province);
            // "type": "1",              --------------地址地址类型 1. 住宅 2.公司 3.学校 4.其他
            String type = dataBean.getType();
            switch (type) {
                case "1":
                    mv.deliveraddress_item_tv_adresstype.setText("住宅");
                    break;
                case "2":
                    mv.deliveraddress_item_tv_adresstype.setText("公司");
                    break;
                case "3":
                    mv.deliveraddress_item_tv_adresstype.setText("学校");
                    break;
                case "4":
                    mv.deliveraddress_item_tv_adresstype.setText("其他");
                    break;
            }
            return super.getView(pos, view, group);
        }

        @Override
        public void onClick(View v) {
            int postion = (int) v.getTag();
            switch (v.getId()) {
                case R.id.deliveraddress_item_bian:

                    DeliverQueryENtity.DataBean dataBean = list.get(postion);
                    String areaid = dataBean.getAreaid();
//                    Log.e("TAG", "onClick: addressid++++++++++++++++++++" + addressid);
                    String city = dataBean.getCity();
                    String province = dataBean.getProvince();
                    String county = dataBean.getCounty();
                    String defaultX = dataBean.getDefaultX();
                    String details = dataBean.getDetails();
                    String phone = dataBean.getPhone();
                    String name = dataBean.getName();
                    String type = dataBean.getType();
                    String latitude = dataBean.getLatitude();
                    String longitude = dataBean.getLongitude();
                    String addressnum = dataBean.getAddressnum();
                    Intent intent = new Intent();
                    intent.setClass(DeliveryaddressActivity.this, NewaddAdders.class);
                    intent.putExtra("chage", "修改");
                    intent.putExtra("name", name);
                    intent.putExtra("phone", phone);
                    intent.putExtra("city", province + city + county);
                    intent.putExtra("areaid", areaid);
                    intent.putExtra("details", details);
                    intent.putExtra("adressnum", addressnum);
                    intent.putExtra("longitude", longitude);
                    intent.putExtra("latitude", latitude);
                    intent.putExtra("default", defaultX);
                    intent.putExtra("type", type);
                    String addressid = dataBean.getAddressid();
                    intent.putExtra("addressid", addressid);
                    startActivity(intent);
                    break;
                case R.id.deliveraddress_item_delete:
                    DeliverQueryENtity.DataBean dataBean1 = list.get(postion);
                    String addressid1 = dataBean1.getAddressid();
                    ShopHttpConfig.App_addressdel(DeliveryaddressActivity.this, addressid1, new Okhttputils.OkutListener() {
                        @Override
                        public void error(Call call, IOException e) {

                        }

                        @Override
                        public void error(Call call, int code) {

                        }

                        @Override
                        public void suseff(Call call, Response response, Object o) {
                            handler.post(new Runnable() {
                                @Override
                                public void run() {
                                    ToastUtil.toast("删除成功");
                                    delivery_address_swp.setRefreshing(true);
                                    onRefresh();
                                }
                            });
                        }
                    }, BaseEntity.class);
                    break;
            }

        }

        class ViewHolder {
            TextView tv_name, deliveraddress_item_defultadderss, deliveraddress_item_tv_phonenum, deliveraddress_item_tv_province,
                    deliveraddress_item_tv_city, deliveraddress_item_tv_county, deliveraddress_item_tv_details, deliveraddress_item_tv_adresstype;
            ImageView deliveraddress_item_bian, deliveraddress_item_delete;
        }
    }

}
